package com.itheima.controller;

import com.itheima.bean.User;
import com.itheima.service.StudentService;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

/**
 * 处理用户登录的请求
 */
@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {

    private UserService userService;

    @Override
    public void init() throws ServletException {
        super.init();
        ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
        userService = ac.getBean("userService", UserService.class);
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1 解决请求和响应中文乱码问题
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //2 获取请求参数并使用BeanUtils封装请求参数
        User user=new User();
        try {
            BeanUtils.populate(user,request.getParameterMap());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //3 调用service层方法,完成登录,得到结果newUser
        User loginUser = userService.login(user);
        //4 判断是否登录成功,如果登录成功就将用户信息保存到session中,响应true
        if(loginUser!=null){
            request.getSession().setAttribute("user",loginUser);
            response.getWriter().write("true");
        }else{
            response.getWriter().write("false");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
